package br.com.persistence;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class FormDao {
	private SQLiteDatabase database;
	private OpenHelper sqliteOpenHelper;
	private String[] columns;

	public FormDao(Context context) {
		sqliteOpenHelper = new OpenHelper(context, null, null, 0);
		
		int n = Form.CHECK_BOX_ARRAY_ID.length + Form.EDIT_TEXT_ARRAY_ID.length + Form.RADIO_BUTTON_ARRAY_ID.length + 1;
		columns = new String[n];
		columns[0] = OpenHelper.COLUMN_ID;
		int i = 1;
		
		for (int id : Form.EDIT_TEXT_ARRAY_ID) {
			columns[i] = OpenHelper.COLUMN_PREFIX + id;
			i++;
		}
		
		for (int id : Form.CHECK_BOX_ARRAY_ID) {
			columns[i] = OpenHelper.COLUMN_PREFIX + id;
			i++;
		}
		
		for (int id : Form.RADIO_BUTTON_ARRAY_ID) {
			columns[i] = OpenHelper.COLUMN_PREFIX + id;
			i++;
		}
		
	}

	public void open() throws SQLException {
		database = sqliteOpenHelper.getWritableDatabase();
	}

	public void close() {
		sqliteOpenHelper.close();
	}

	public Form create(Form form) {
		ContentValues values = new ContentValues();
		
		HashMap<String, String> field = form.getformMap();
		
		foreachValuesPut(Form.EDIT_TEXT_ARRAY_ID, field, values);
		foreachValuesPut(Form.CHECK_BOX_ARRAY_ID, field, values);
		foreachValuesPut(Form.RADIO_BUTTON_ARRAY_ID, field, values);
		
		long insertId = database.insert(OpenHelper.TABLE_NAME,
				null, values);
		
		Cursor cursor = database.query(OpenHelper.TABLE_NAME,
				columns, OpenHelper.COLUMN_ID + " = " + insertId,
				null, null, null, null);
		cursor.moveToFirst();
		Form newForm = new Form(cursor);
		cursor.close();

		return newForm;
	}
	
	public void foreachValuesPut(int[] arrayId, HashMap<String, String> field, ContentValues values){
		for (int id : arrayId) {
			String tableName = OpenHelper.COLUMN_PREFIX + id;
			values.put(tableName, field.get(tableName));
		}
	}

	public void delete(Form form) {
		long id = form.getId();
		database.delete(OpenHelper.TABLE_NAME,
				OpenHelper.COLUMN_ID + " = " + id, null);
	}
	
	public List<Form> getAll(){
		
		List<Form>forms = new ArrayList<Form>();
				
		Cursor cursor = database.query(OpenHelper.TABLE_NAME,
		columns, null, null, null, null, null);
				
		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			Form form = new Form(cursor);
			forms.add(form);
			cursor.moveToNext();
		}
		cursor.close();
		return forms;
		}

}